package stardust.product.utils.baby;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.htmlparser.util.Translate;
import stardust.core.io.IOUtils;
import stardust.core.network.protocol.http.HttpClient;
import stardust.core.network.protocol.http.HttpMethod;
import stardust.core.network.protocol.http.HttpResponseMeta;
import stardust.core.support.conversion.StringConversion;
import stardust.product.xspider.support.HTMLSupport;

public class Amazon2
{

  public static void main(String[] args) throws IOException
  {
    String file = "" + "report-" + StringConversion.parseDate(new Date(), "yyyy年MM月dd日hh时mm分ss秒") + ".csv";
    IOUtils.write(file, new byte[0], false);
    IOUtils.write(file, "来源文件,商品链接,订单发生日期,订单编号,商品编码,尺码,销售数量,销售总额,收货人信息\n".getBytes(), true);
    
    File[] files = new File(".").listFiles();
    for (File i : files)
    {
      if (i.isDirectory() || !(i.getName().toLowerCase().endsWith(".htm") || i.getName().toLowerCase().endsWith(".html")))
      {
        continue;
      }
      
      byte[] data = IOUtils.read(i);
      String html = new String(data, "UTF-8");
      
      List<OrderInfo> orders = Amazon2.analyseOrderInfo(file, i.getName(), html);
      OrderInfo o;
      
      for (int j = 0; j < orders.size(); j++)
      {
        o = orders.get(j);
        
        IOUtils.write(file, 
            ("\"" + o.TAG + "\"," +
            "\"" + o.goodsLink + "\"," +
            "\"" + o.orderCreateDate + "\"," +
            "\"" + o.orderNo + "\"," +
            "\"" + o.goodsNo + "\"," +
            "\"" + o.size + "\"," +
            "\"" + o.goodsCount + "\"," +
            "\"" + o.sale + "\"," +
            "\"" + o.man + "    " + o.address + "    " + o.phone + "\"\r\n").getBytes(), true);
      }
    }
  }
  
  public static List<OrderInfo> analyseOrderInfo(String output, String srcFile, String html) throws IOException
  {
    List<OrderInfo> orders = new ArrayList<OrderInfo>();
    
    try
    {
      // 提取订单编号。
      String orderNoTextBegin = "订单编号：";
      String orderNoTextEnd = "\n";
      int orderNoBegin = html.indexOf(orderNoTextBegin);
      int orderNoEnd = html.indexOf(orderNoTextEnd, orderNoBegin);
      String orderNo = html.substring(orderNoBegin + orderNoTextBegin.length(), orderNoEnd).trim();
      
      // 提取购买日期。
      String orderCreateDateTextBegin0 = "购买日期：</td>";
      String orderCreateDateTextBegin1 = ">";
      String orderCreateDateTextEnd = "</td>";
      int orderCreateDateBegin0 = html.indexOf(orderCreateDateTextBegin0);
      int orderCreateDateBegin = html.indexOf(orderCreateDateTextBegin1, orderCreateDateBegin0 + orderCreateDateTextBegin0.length());
      int orderCreateDateEnd = html.indexOf(orderCreateDateTextEnd, orderCreateDateBegin);
      String orderCreateDate = Translate.decode(html.substring(orderCreateDateBegin + orderCreateDateTextBegin1.length(), orderCreateDateEnd));
    
      // 提取商品信息。
      List<String> good = new ArrayList<String>();
      List<String> goodLink = new ArrayList<String>();
      int goodOffset = 0;
      
      try
      {
        for (int i = 0; i < 10; i++)
        {
          String goodTextBegin0 = "<span class=\"smaller\"><strong><a href=";
          String goodTextBegin1 = ">";
          String goodTextEnd0 = "</a>";
          int goodBegin0 = html.indexOf(goodTextBegin0, goodOffset);
          if (goodBegin0 == -1) break;
          int goodBegin = html.indexOf(goodTextBegin1, goodBegin0 + goodTextBegin0.length());
          int goodEnd = html.indexOf(goodTextEnd0, goodBegin);
          String goodLinkTempString = html.substring(goodBegin0 + goodTextBegin0.length() + 1, goodBegin - 1);
          goodLink.add(goodLinkTempString);
          String goodTempString = Translate.decode(html.substring(goodBegin + goodTextBegin1.length(), goodEnd));
          goodOffset = goodBegin;
          good.add(goodTempString);
        }
      }
      catch (Exception e)
      {
        System.out.println(e);
      }
      
      // 提取商品价格。
      List<String> sale = new ArrayList<String>();
      int saleOffset = 0;
      
      try
      {
        for (int i = 0; i < 10; i++)
        {
          String saleTextBegin0 = "<td class=\"smaller\" align=\"right\" nowrap>￥";
          String saleTextEnd0 = "</td>";
          int saleBegin = html.indexOf(saleTextBegin0, saleOffset);
          if (saleBegin == -1) break;
          int saleEnd = html.indexOf(saleTextEnd0, saleBegin);
          sale.add(html.substring(saleBegin + saleTextBegin0.length(), saleEnd));
          saleOffset = saleEnd;
        }
      }
      catch (Exception e)
      {
        System.out.println(e);
      }
      
      // 提取商品销售数量。
      List<String> count = new ArrayList<String>();
      int countOffset = 0;
      
      try
      {
        for (int i = 0; i < 10; i++)
        {
          String countTextEnd = "<td class=\"data-display-field\" align=\"center\" valign=\"top\">￥";
          int countEnd = html.indexOf(countTextEnd, countOffset);
          if (countEnd == -1) break;
          count.add(getCount(html, countEnd));
          countOffset = countEnd + 1;
        }
      }
      catch (Exception e)
      {
        System.out.println(e);
      }
      
      // 提取配送地址。
      String address = "", man = "", phone = "";
      
      String addressTextBegin = "配送地址</strong><br>";
      String addressTextEnd = "</td>";
      int addressBegin = html.indexOf(addressTextBegin);
      int addressEnd = html.indexOf(addressTextEnd, addressBegin);
      String addressTempString = html.substring(addressBegin + addressTextBegin.length(), addressEnd);
      
      String[] addressTempStringArray = addressTempString.replaceAll("<br>", "\n").split("\n");
      for (int i = 0; i < addressTempStringArray.length; i++)
      {
        if (i == 0)
        {
          man = addressTempStringArray[i];
        }
        else if (i == addressTempStringArray.length - 1)
        {
          phone = addressTempStringArray[i].substring(3);
        }
        else
        {
          if (i == addressTempStringArray.length - 2)
          {
            String addressTempString1 = Translate.decode(addressTempStringArray[i]);
            addressTempString1 = addressTempString1.replaceAll(",", " ").replaceAll(" ", " ");
            String[] addressTempStringArray1 = addressTempString1.split(" ");
            addressTempString1 = "";
            
            for (int j = 0; j < addressTempStringArray1.length; j++)
            {
              if (j == addressTempStringArray1.length - 1)
              {
                // 邮编加到末尾。
                address = address + "," + addressTempStringArray1[j];
              }
              else
              {
                addressTempString1 = addressTempStringArray1[j] + addressTempString1;
              }
            }
            
            address = addressTempString1 + "," + address;
          }
          else
          {
            address = address + Translate.decode(addressTempStringArray[i]);
          }
        }
        
      }
      
      for (int i = 0; i < good.size() && i < goodLink.size() && i < sale.size() && i < count.size(); i++)
      {
        OrderInfo o = new OrderInfo();
        
        o.TAG = srcFile;
        
        o.goodsLink = goodLink.get(i);
        String goodsName0 = good.get(i);
        String goodsName1 = getGoodsName(o.goodsLink);
        
        o.orderCreateDate = orderCreateDate.split(" ")[0].replaceAll("年|月", "-").replaceAll("日", "");
        o.orderNo = orderNo.replaceAll("\"", "\\\"");
        o.goodsNo = (getBianma(goodsName0).isEmpty() ? getBianma(goodsName1) : getBianma(goodsName0)).replaceAll("\"", "\\\"");
        
        if (!getChima(goodsName0).isEmpty() || !getChima2(goodsName0).isEmpty())
        {
          o.size = getChima(goodsName0).isEmpty() ? getChima2(goodsName0) : getChima(goodsName0);
        }
        else
        {
          o.size = getChima(goodsName1).isEmpty() ? getChima2(goodsName1) : getChima(goodsName1);
        }
        o.goodsCount = count.get(i);
        o.sale = sale.get(i).replaceAll("\"", "\\\"");
        o.address = address.replaceAll("\"", "\\\"").replaceAll("\\?", "");
        o.man = man.replaceAll("\"", "\\\"");
        o.phone = phone.replaceAll("\"", "\\\"");
        
        orders.add(o);
      }
      
      System.out.println("成功：" + srcFile);
    }
    catch (Exception e)
    {
      System.out.println("失败：" + srcFile);
      e.printStackTrace();
    }
    
    return orders;
  }
  
  public static String getChima(String str)
  {
    String chimaTextBegin0 = "（";
    String chimaTextBegin1 = "(";
    
    String chimaTextEnd0 = "）";
    String chimaTextEnd1 = ")";
    
    int chimaBegin = str.indexOf(chimaTextBegin0) == -1 ? str.indexOf(chimaTextBegin1) : str.indexOf(chimaTextBegin0);
    int chimaEnd = str.indexOf(chimaTextEnd0) == -1 ? str.indexOf(chimaTextEnd1) : str.indexOf(chimaTextEnd0);
    
    if (chimaBegin == -1)
    {
      return "";
    }
    else if (chimaEnd == -1)
    {
      return str.substring(chimaBegin + chimaTextBegin0.length());
    }
    else
    {
      return str.substring(chimaBegin + chimaTextBegin0.length(), chimaEnd).trim();
    }
  }
  
  public static String getChima2(String str)
  {
    String bianma = getBianma(str);
    
    if (bianma.isEmpty())
    {
      return "";
    }
    
    int chimaBegin = str.lastIndexOf(bianma);
    
    if (chimaBegin == -1)
    {
      return "";
    }
    else
    {
      return str.substring(chimaBegin + bianma.length()).trim();
    }
  }
  
  public static String getBianma(String str)
  {
    String bianma = "";
    
    for (int i = 0; i < str.length(); i++)
    {
      if (Character.isDigit(str.charAt(i)) || ((str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') || (str.charAt(i) >= 'a' && str.charAt(i) <= 'z')))
      {
        bianma += str.charAt(i);
      }
      else if (!bianma.endsWith(" "))
      {
        bianma += " ";
      }
    }
    
    String[] bianmaArray = bianma.split(" ");
    
    bianma = "";
    for (int i = 0; i < bianmaArray.length; i++)
    {
      if (bianmaArray[i].length()  == 13)
      {
        bianma = bianmaArray[i];
      }
    }
    
    return bianma;
  }
  
  public static String getGoodsName(String link) throws IOException
  {
    HttpClient http = new HttpClient();
    HttpResponseMeta rsp = http.go(link, HttpMethod.get);
    http.disconnect();
    
    String html = new String(rsp.getData(), "UTF-8");
    
    String titleTextBegin = "<title>";
    String titleTextEnd = "</title>";
    int titleBegin = html.indexOf(titleTextBegin);
    int titleEnd = html.indexOf(titleTextEnd, titleBegin);
    
    html = html.substring(titleBegin + titleTextBegin.length(), titleEnd);
    html = html.replaceAll("-亚马逊中国", "");
    titleEnd = html.lastIndexOf("-");
    html = html.substring(0, titleEnd).replaceAll("�", "");
    
    return html;
  }

  public static String getCount(String html, int offset)
  {
    offset--;
    
    int beginFlag = 0, endFlag = 0;
    int beginOffset = -1, endOffset = -1;
    
    for (int i = offset; i >= 0; i--)
    {
      if (html.charAt(i) == '<')
      {
        beginFlag++;
        
        if (beginFlag == 3)
        {
          endOffset = i;
        }
      }
      else if (html.charAt(i) == '>' && endOffset != -1)
      {
        beginOffset = i;
        break;
      }
    }
    
    return html.substring(beginOffset + 1, endOffset);
  }
  
}
